from flask import Flask,jsonify
from flask_restful import Resource, Api
from flask_cors import *

import pymongo
import json
import bson
from bson import Binary, Code,json_util
from wordcloud import WordCloud,STOPWORDS

import matplotlib.pyplot as plt
import math
from matplotlib.font_manager import FontProperties

app = Flask(__name__)
CORS(app, supports_credentials=True)

api = Api(app)

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["scrapy"]
myc1 = mydb["collections1"]
font = FontProperties(fname=r"/code/simhei.ttf")

class HelloWorld(Resource):
    def options(self):
        return {'Allow': '*'}, 200, {'Access-Control-Allow-Origin': '*',
                                     'Access-Control-Allow-Methods': 'HEAD, OPTIONS, GET, POST, DELETE, PUT',
                                     'Access-Control-Allow-Headers': '*'
                                     }
    def get(self):
        L=[]
        L.append({'hello': 'world'})
        datalist = myc1.find_one()
        d = json_util.dumps(datalist)#dict
        dd = json.loads(d)
        L.append(dd)
        return jsonify(L)

class SelectAll(Resource):
    def options(self):
        return {'Allow': '*'}, 200, {'Access-Control-Allow-Origin': '*',
                                     'Access-Control-Allow-Methods': 'HEAD, OPTIONS, GET, POST, DELETE, PUT',
                                     }
    def get(self):
        L=[]
        datalists = myc1.find()
        for x in datalists:
            tmp = json_util.dumps(x)
            data = json.loads(tmp)
            #print(data)
            L.append(data)
        return jsonify(L)

class gen_hist(Resource):  ## 定时通过另外一个docker服务刷新
    def option(self):
        return {'Allow': '*'}, 200, {'Access-Control-Allow-Origin': '*',
                                     'Access-Control-Allow-Methods': 'HEAD, OPTIONS, GET, POST, DELETE, PUT',
                                     }
    def get(self):
        dataaggr = myc1.aggregate([
        {
            '$group': {
                '_id': '$name', 
                'fieldN': {
                    '$count': {}
                }
            }
        }, 
        {
            '$sort': {
                'fieldN': -1
            }
        }
    ])
        names=[]
        counts=[]
        plt.style.use('ggplot')
        plt.figure(dpi=300).set_size_inches(8, 4)
        for x in dataaggr:
            name = x["_id"]
            count = x["fieldN"]
            #print(name,count)
            names.append(name)
            counts.append(count)
        x_pos = [i for i, _ in enumerate(names)]
        #print(x_pos)
        bins_scope=[0,1,2,3,4,5,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180]
        plt.hist( counts, bins=bins_scope,color='blue')
        plt.xlabel("同一名称出现次数频数(个数)",fontproperties=font)
        plt.ylabel("频率段数量(次)",fontproperties=font)
        plt.yscale("log")
        plt.title("出现次数频数",fontproperties=font)
        plt.xticks(bins_scope)
        plt.savefig("/code/storage/gen_hist.jpg")
 
        return jsonify({"state":"success"})

class gen_wordcloud(Resource):
    def option(self):
        return {'Allow': '*'}, 200, {'Access-Control-Allow-Origin': '*',
                                     'Access-Control-Allow-Methods': 'HEAD, OPTIONS, GET, POST, DELETE, PUT',
                                     }
    def get(self):
        dataaggr = myc1.aggregate([
        {
            '$group': {
                '_id': '$name', 
                'fieldN': {
                    '$count': {}
                }
            }
        }, 
        {
            '$sort': {
                'fieldN': -1
            }
        }
    ])
        names=[]
        counts=[]
        txt = " "
        stopwords= STOPWORDS
        st = ["de","la","und","et","Le"]
        for x in st:
            stopwords.add(x)
        for x in dataaggr:
            name = x["_id"]
            count = x["fieldN"]
            #print(name,count)
            names.append(name)
        w = WordCloud(width=1366, height=768,stopwords=stopwords,background_color="white")
        w.generate(txt.join(names))
        w.to_file(r"/code/storage/gen_wordcloud.jpg")
        return jsonify({"state":"success"})

api.add_resource(HelloWorld, '/')
api.add_resource(SelectAll,'/v1/collection1/select/')
api.add_resource(gen_hist ,'/v1/collection2/gen_hist/')
api.add_resource(gen_wordcloud,'/v1/collection2/gen_wordcloud/')

if __name__ == '__main__':
    print("version 01")
    app.run("0.0.0.0","5000")